<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        v-model:query="filterInfo.query.queryMap"
        :queryMoreJson="true"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :clearType="clearType"
        :slipSelectRequest="slipSelectRequest"
        ref="pageFilter"
      >
        <template v-slot:filter-localDate>
          <el-date-picker
            @change="timeChange"
            v-model="localDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="datetimerange"
            range-separator="至"
            :shortcuts="$fn.pickerOptionsFn()"
            align="right"
            start-placeholder="操作时间开始日期"
            end-placeholder="操作时间结束日期"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59),
            ]"
          ></el-date-picker>
        </template>
      </NewPageFilter>
    </div>

    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList">
        <template v-slot:filter-print>
          <el-button
            v-if="$permission('equipmentMaintenanceTimes:print')"
            @click="print"
            >打印</el-button
          >
        </template>
        <template v-slot:filter-excel>
          <el-button
            v-if="$permission('equipmentMaintenanceTimes:excel')"
            @click="exportExcel"
            >导出excel</el-button
          >
        </template>
      </NewPageFilter>
      <div class="display-flex">
        <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <TableContainer
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :summary="true"
      :summaryFieldList="tableInfo.summaryFieldList"
      :tab-index="true"
      :check-box="false"
      v-model:query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      @sortChange="sortChange"
      @handleEvent="handleEvent"
    >
    </TableContainer>

    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :fieldList="tableInfo.fieldList"
      v-model:formData="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<script setup name="equipmentMaintenanceTimes">
import {
  printEquipmentMaintenanceTimes,
  getEquipmentMaintenanceTimesCustomizeList,
  exportEquipmentMaintenanceTimes,
} from '@/api/dataQuery.js'
import moment from 'moment'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
const { proxy } = getCurrentInstance()
const props = defineProps(['query'])
const clearType = ref(true)
const slipSelectRequest = ref(true)
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      deptAuth: {
        asTbName: 'join_query',
        columnName: 'use_dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      localDate: {
        queryType: 'BETWEEN',
        value:
          moment(
            new Date(new Date().getFullYear(), new Date().getMonth(), 1)
          ).format('YYYY-MM-DD') +
          ',' +
          moment(new Date()).format('YYYY-MM-DD'),
      },
    },
    groupMap: {},
    groups: [],
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'print',
      type: 'slot',
    },
    {
      value: 'excel',
      type: 'slot',
    },
  ],
})
const localDate = ref([
  moment(new Date(new Date().getFullYear(), new Date().getMonth(), 1)).format(
    'YYYY-MM-DD'
  ),
  moment(new Date()).format('YYYY-MM-DD'),
])

const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  summaryFieldList: [
    { value: 'repairTimes', formatter: proxy.$fn.qtyFormatter }
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [],
  },
})
const preferenceInfo = ref({
  visible: false,
})

const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  let arr = [
    {
      asTbName: 'depot_stock_affair',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
    {
      asTbName: 'depot_stock_affair',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
async function getList() {
  tableInfo.value.refresh = Math.random()
}

function search() {
  if (localDate.value) {
    let startTime =
      typeof localDate.value[0] === 'string'
        ? new Date(localDate.value[0])
        : localDate.value[0]
    let endTime =
      typeof localDate.value[1] === 'string'
        ? new Date(localDate.value[1])
        : localDate.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('时间间隔不能超过一年！')
    } else {
      doSearch()
    }
  } else {
    doSearch()
    //proxy.$message.warning('请选择时间')
  }
}
function doSearch() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  localDate.value = null
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'EquipmentMaintenanceTimesList-com.slip.spd.entity.dto.dataquery.EquipmentMaintenanceTimesDTO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )

      tableInfo.value.fieldList = tableFieldInfo.fieldList
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      let queryIn = proxy.$route.params.query
      if (queryIn) {
        filterInfo.value.query.queryMap = {
          ...filterInfo.value.query.queryMap,
          ...queryIn.queryMap,
        }
        if (queryIn.queryMap.localDate) {
          localDate.value = queryIn.queryMap.localDate.value.split(',')
        }
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      let arr = [
        /* {
          label: '时间',
          value: 'time',
          componentType: 'dateTime',
          slot: true,
          show: true,
          hidden: true,
        }, */
      ]
      filterInfo.value.searchList = arr.concat(filterInfo.value.searchList)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getEquipmentMaintenanceTimesCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.toString()
    getList()
  }
}

function exportExcel() {
  if (localDate.value) {
    let startTime =
      typeof localDate.value[0] === 'string'
        ? new Date(localDate.value[0])
        : localDate.value[0]
    let endTime =
      typeof localDate.value[1] === 'string'
        ? new Date(localDate.value[1])
        : localDate.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      exportEquipmentMaintenanceTimes(
        proxy.$fn.delEmptyAttribute(filterInfo.value.query)
      ).then((resp) => {
        if (resp) {
          proxy.$fn.parseExcel(resp)
        }
      })
    }
  } else {
    proxy.$message.warning('请选择时间')
  }
}

function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryMap.localDate.value = val[0] + ',' + val[1]
  } else {
    filterInfo.value.query.queryMap.localDate.value = null
  }
}
//打印
function print() {
  if (localDate.value) {
    let startTime =
      typeof localDate.value[0] === 'string'
        ? new Date(localDate.value[0])
        : localDate.value[0]
    let endTime =
      typeof localDate.value[1] === 'string'
        ? new Date(localDate.value[1])
        : localDate.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      fatchTemplateByCode({
        resourceCode: 'equipmentMaintenanceTimes:print',
        isDefault: 1,
      }).then((res) => {
        if (res && res.success) {
          let temp = proxy.$fn.getPrintTemp(res.data[0])
          getPrintData(temp)
        }
      })
    }
  } else {
    proxy.$message.warning('请选择时间')
  }
}
function getPrintData(temp) {
  let params = {
    customizeDto: filterInfo.value.query,
  }
  printEquipmentMaintenanceTimes(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('supplierPurchRateQuery:price')
      )
    }
  })
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}

let obj = {
  assetName: {
    label: '资产名称',
    value: 'assetName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
